#include <string.h>
#include "esp_log.h"
#include "esp_bt.h"

#include "esp_gap_ble_api.h"
#include "esp_gatts_api.h"
#include "esp_bt_defs.h"
#include "esp_bt_main.h"
#include "esp_bt_device.h"
#include "esp_gatt_common_api.h"

#include "ble.h"
#include "motor.h"
#include "atomizer.h"

#define GATTS_TAG "BLE_APP"

#define ADV_CONFIG_FLAG      (1 << 0)
#define SCAN_RSP_CONFIG_FLAG (1 << 1)

static esp_gatt_char_prop_t imu_property = 0;
static esp_gatt_char_prop_t motor_property = 0;
static esp_gatt_char_prop_t atomizer_property = 0;
static bool imu_create_cmpl = false;  // IMU Service
static bool imu_notify_enabled = false;
static bool motor_create_cmpl = false;  // Motor Service
static bool atomizer_create_cmpl = false;  // Atomizer Service
static uint8_t adv_config_done = 0;

uint8_t imu_data_val[6] = {0};
float motor_duty_rate_val = 0;
float atomizer_duty_rate_val = 0;

static void imu_gatts_profile_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
static void motor_gatts_profile_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
static void atomizer_gatts_profile_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);


static esp_attr_value_t imu_data_attr = {
    .attr_max_len = 6,
    .attr_len     = sizeof(imu_data_val),
    .attr_value   = imu_data_val,
};

static esp_attr_value_t motor_duty_rate_attr = {
    .attr_max_len = 4,
    .attr_len     = sizeof(motor_duty_rate_val),
    .attr_value   = (uint8_t *)&motor_duty_rate_val,
};

static esp_attr_value_t atomizer_status_attr = {
    .attr_max_len = 1,
    .attr_len     = sizeof(atomizer1.enable_flag),
    .attr_value   = (uint8_t *)&atomizer1.enable_flag,
};

static esp_attr_value_t atomizer_duty_rate_attr = {
    .attr_max_len = 4,
    .attr_value   = (uint8_t *)&atomizer_duty_rate_val,
};

// IMU特征使用自定义128位UUID
static const uint8_t imu_chr_uuid[] = {
    0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00};

// Motor和Atomizer使用示例的LED UUID（nRF Connect识别为开关）
static const uint8_t led_chr_uuid[] = {
    0x23, 0xd1, 0xbc, 0xea, 0x5f, 0x78, 0x23, 0x15, 0xde, 0xef, 0x12, 0x12, 0x25, 0x15, 0x00, 0x00};

static esp_ble_adv_data_t adv_data = {
    .set_scan_rsp = false,
    .include_name = true,
    .include_txpower = false,
    .min_interval = 0x0006,
    .max_interval = 0x0010,
    .appearance = 0x00,
    .manufacturer_len = 0,
    .p_manufacturer_data =  NULL,
    .service_data_len = 0,
    .p_service_data = NULL,
    .service_uuid_len = 0,
    .p_service_uuid = NULL,
    .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT),
};

static esp_ble_adv_params_t adv_params = {
    .adv_int_min        = 0x20,  // 20ms
    .adv_int_max        = 0x40,  // 40ms
    .adv_type           = ADV_TYPE_IND,
    .own_addr_type      = BLE_ADDR_TYPE_PUBLIC,
    .channel_map        = ADV_CHNL_ALL,
    .adv_filter_policy  = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
};

struct gatts_profile_inst gl_profile_tab[PROFILE_NUM] = {
    [IMU_PROFILE_APP_ID] = {
        .gatts_cb = imu_gatts_profile_event_handler,
        .gatts_if = ESP_GATT_IF_NONE,       /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
    },
    [MOTOR_PROFILE_APP_ID] = {
        .gatts_cb = motor_gatts_profile_event_handler,
        .gatts_if = ESP_GATT_IF_NONE,       /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
    },
    [ATOMIZER_PROFILE_APP_ID] = {
        .gatts_cb = atomizer_gatts_profile_event_handler,
        .gatts_if = ESP_GATT_IF_NONE,       /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
    },
};

void example_write_event_env(esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
{
    esp_gatt_status_t status = ESP_GATT_OK;
    if (param->write.need_rsp) {
        esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, status, NULL);
    }
}

void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
    switch (event) {
    case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT:
        ESP_LOGI(GATTS_TAG, "Advertising data set, status %d", param->adv_data_cmpl.status);
        adv_config_done &= (~ADV_CONFIG_FLAG);
        if (adv_config_done == 0) {
            esp_ble_gap_start_advertising(&adv_params);
        }
        break;
    case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT:
        ESP_LOGI(GATTS_TAG, "Scan response data set, status %d", param->scan_rsp_data_cmpl.status);
        adv_config_done &= (~SCAN_RSP_CONFIG_FLAG);
        if (adv_config_done == 0) {
            esp_ble_gap_start_advertising(&adv_params);
        }
        break;
    case ESP_GAP_BLE_ADV_START_COMPLETE_EVT:
        if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS) {
            ESP_LOGE(GATTS_TAG, "Advertising start failed, status %d", param->adv_start_cmpl.status);
            break;
        }
        ESP_LOGI(GATTS_TAG, "Advertising start successfully");
        break;
    case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT:
        ESP_LOGI(GATTS_TAG, "Connection params update, status %d, conn_int %d, latency %d, timeout %d",
                 param->update_conn_params.status,
                 param->update_conn_params.conn_int,
                 param->update_conn_params.latency,
                 param->update_conn_params.timeout);
        break;
    case ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT:
        ESP_LOGI(GATTS_TAG, "Packet length update, status %d, rx %d, tx %d",
                 param->pkt_data_length_cmpl.status,
                 param->pkt_data_length_cmpl.params.rx_len,
                 param->pkt_data_length_cmpl.params.tx_len);
        break;
    default:
        break;
    }
}

static void imu_gatts_profile_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
{
    esp_err_t ret;
    switch (event) {
    case ESP_GATTS_REG_EVT:
        ESP_LOGI(GATTS_TAG, "GATT server register, status %d, app_id %d", param->reg.status, param->reg.app_id);
        gl_profile_tab[IMU_PROFILE_APP_ID].service_id.is_primary = true;
        gl_profile_tab[IMU_PROFILE_APP_ID].service_id.id.inst_id = 0x00;
        gl_profile_tab[IMU_PROFILE_APP_ID].service_id.id.uuid.len = ESP_UUID_LEN_16;
        gl_profile_tab[IMU_PROFILE_APP_ID].service_id.id.uuid.uuid.uuid16 = IMU_SVC_UUID;

        //config adv data
        ret = esp_ble_gap_config_adv_data(&adv_data);
        if (ret) {
            ESP_LOGE(GATTS_TAG, "config adv data failed, error code = %x", ret);
            break;
        }

        esp_ble_gatts_create_service(gatts_if, &gl_profile_tab[IMU_PROFILE_APP_ID].service_id, IMU_NUM_HANDLE);
        break;
    case ESP_GATTS_CREATE_EVT:
        //service has been created, now add characteristic declaration
        ESP_LOGI(GATTS_TAG, "Service create, status %d, service_handle %d", param->create.status, param->create.service_handle);
        gl_profile_tab[IMU_PROFILE_APP_ID].service_handle = param->create.service_handle;
        gl_profile_tab[IMU_PROFILE_APP_ID].char_uuid.len = ESP_UUID_LEN_128;
        memcpy(gl_profile_tab[IMU_PROFILE_APP_ID].char_uuid.uuid.uuid128, imu_chr_uuid, ESP_UUID_LEN_128);

        esp_ble_gatts_start_service(gl_profile_tab[IMU_PROFILE_APP_ID].service_handle);
        imu_property = ESP_GATT_CHAR_PROP_BIT_READ | ESP_GATT_CHAR_PROP_BIT_NOTIFY;
        ret = esp_ble_gatts_add_char(gl_profile_tab[IMU_PROFILE_APP_ID].service_handle, &gl_profile_tab[IMU_PROFILE_APP_ID].char_uuid,
                            ESP_GATT_PERM_READ,
                            imu_property,
                            &imu_data_attr, NULL);
        if (ret) {
            ESP_LOGE(GATTS_TAG, "add char failed, error code = %x", ret);
        }
        break;
    case ESP_GATTS_ADD_CHAR_EVT:
        ESP_LOGI(GATTS_TAG, "Characteristic add, status %d, attr_handle %d, char_uuid %x",
                 param->add_char.status, param->add_char.attr_handle, param->add_char.char_uuid.uuid.uuid16);
        gl_profile_tab[IMU_PROFILE_APP_ID].char_handle = param->add_char.attr_handle;
        gl_profile_tab[IMU_PROFILE_APP_ID].descr_uuid.len = ESP_UUID_LEN_16;
        gl_profile_tab[IMU_PROFILE_APP_ID].descr_uuid.uuid.uuid16 = ESP_GATT_UUID_CHAR_CLIENT_CONFIG;
        ESP_LOGI(GATTS_TAG, "imu char handle %d", param->add_char.attr_handle);
        ret = esp_ble_gatts_add_char_descr(gl_profile_tab[IMU_PROFILE_APP_ID].service_handle, &gl_profile_tab[IMU_PROFILE_APP_ID].descr_uuid,
                            ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, NULL, NULL);
        if (ret) {
            ESP_LOGE(GATTS_TAG, "add char descr (CCCD) failed, error code = %x", ret);
        }
        break;
    case ESP_GATTS_ADD_CHAR_DESCR_EVT:
        ESP_LOGI(GATTS_TAG, "Descriptor add, status %d, attr_handle %u",
                 param->add_char_descr.status, param->add_char_descr.attr_handle);
        gl_profile_tab[IMU_PROFILE_APP_ID].descr_handle = param->add_char_descr.attr_handle;
        imu_create_cmpl = true;
        break;
    case ESP_GATTS_READ_EVT:
        ESP_LOGI(GATTS_TAG, "Read request, handle=%d", param->read.handle);
        esp_gatt_rsp_t rsp;
        memset(&rsp, 0, sizeof(esp_gatt_rsp_t));
        rsp.attr_value.handle = param->read.handle;
        
        // 区分读取的是特征值还是CCCD
        if (param->read.handle == gl_profile_tab[IMU_PROFILE_APP_ID].char_handle) {
            // 读取特征值：返回6字节IMU数据
            ESP_LOGI(GATTS_TAG, "Reading characteristic value (IMU data)");
            rsp.attr_value.len = sizeof(imu_data_val);
            memcpy(rsp.attr_value.value, imu_data_val, sizeof(imu_data_val));
        } else if (param->read.handle == gl_profile_tab[IMU_PROFILE_APP_ID].descr_handle) {
            // 读取CCCD：返回2字节配置值
            ESP_LOGI(GATTS_TAG, "Reading CCCD value");
            rsp.attr_value.len = 2;
            // CCCD值：0x0000=禁用, 0x0001=notify启用, 0x0002=indicate启用
            uint16_t cccd_value = imu_notify_enabled ? 0x0001 : 0x0000;
            rsp.attr_value.value[0] = cccd_value & 0xFF;        // 低字节
            rsp.attr_value.value[1] = (cccd_value >> 8) & 0xFF; // 高字节
        } else {
            ESP_LOGW(GATTS_TAG, "Unknown handle for read: %d", param->read.handle);
        }
        
        esp_ble_gatts_send_response(gatts_if, param->read.conn_id, param->read.trans_id, ESP_GATT_OK, &rsp);
        break;
    case ESP_GATTS_WRITE_EVT:
        ESP_LOGI(GATTS_TAG, "characteristic write, handle=%d, descr_handle=%d, len=%u", 
                 param->write.handle, gl_profile_tab[IMU_PROFILE_APP_ID].descr_handle, param->write.len);
        ESP_LOG_BUFFER_HEX(GATTS_TAG, param->write.value, param->write.len);
        if (param->write.handle == gl_profile_tab[IMU_PROFILE_APP_ID].descr_handle && param->write.len == 2){
            uint16_t descr_value = param->write.value[1]<<8 | param->write.value[0];
            ESP_LOGI(GATTS_TAG, "CCCD write detected, value=0x%04x", descr_value);
            if (descr_value == 0x0001){
                if (imu_property & ESP_GATT_CHAR_PROP_BIT_NOTIFY) {
                    ESP_LOGI(GATTS_TAG, "notify enable");
                    imu_notify_enabled = true;
                    // 立即发送一次初始数据，确认notify已启用
                    uint8_t notify_data[6] = {0};
                    memcpy(notify_data, imu_data_val, sizeof(imu_data_val));
                    ESP_LOGI(GATTS_TAG, "sending initial notify data");
                    ret = esp_ble_gatts_send_indicate(gatts_if, param->write.conn_id, 
                                                       gl_profile_tab[IMU_PROFILE_APP_ID].char_handle,
                                                       sizeof(notify_data), notify_data, false);
                    if (ret) {
                        ESP_LOGE(GATTS_TAG, "Send initial notify failed, error code = %x", ret);
                    }
                }
            }else if (descr_value == 0x0000){
                ESP_LOGI(GATTS_TAG, "notify disable");
                imu_notify_enabled = false;
            }
        }
        example_write_event_env(gatts_if, param);
        break;
    case ESP_GATTS_DELETE_EVT:
        break;
    case ESP_GATTS_START_EVT:
        ESP_LOGI(GATTS_TAG, "service start, status %d, service_handle %d", param->start.status, param->start.service_handle);
        break;
    case ESP_GATTS_STOP_EVT:
        break;
    case ESP_GATTS_CONNECT_EVT:
        ESP_LOGI(GATTS_TAG, "connected, conn_id %u, remote "ESP_BD_ADDR_STR"",
                param->connect.conn_id, ESP_BD_ADDR_HEX(param->connect.remote_bda));
        gl_profile_tab[IMU_PROFILE_APP_ID].conn_id = param->connect.conn_id;
        break;
    case ESP_GATTS_DISCONNECT_EVT:
        ESP_LOGI(GATTS_TAG, "disconnected, remote "ESP_BD_ADDR_STR", reason 0x%02x",
                 ESP_BD_ADDR_HEX(param->disconnect.remote_bda), param->disconnect.reason);
        imu_notify_enabled = false;
        esp_ble_gap_start_advertising(&adv_params);
        break;
    case ESP_GATTS_CONF_EVT:
        ESP_LOGI(GATTS_TAG, "confirm receive, status %d, attr_handle %d", param->conf.status, param->conf.handle);
        if (param->conf.status != ESP_GATT_OK) {
            ESP_LOG_BUFFER_HEX(GATTS_TAG, param->conf.value, param->conf.len);
        }
        break;
    case ESP_GATTS_SET_ATTR_VAL_EVT:
        // ESP_LOGI(GATTS_TAG, "attribute value set, status %d, imu_notify_enabled=%d", param->set_attr_val.status, imu_notify_enabled);
        if (imu_notify_enabled) {
            uint8_t notify_data[6] = {0};
            memcpy(notify_data, imu_data_val, sizeof(imu_data_val));
            ESP_LOGI(GATTS_TAG, "sending notify: x=%d, y=%d, z=%d", 
                     *((int16_t*)&notify_data[0]), *((int16_t*)&notify_data[2]), *((int16_t*)&notify_data[4]));
            // 使用false表示notification模式（与property中的NOTIFY匹配）
            ret = esp_ble_gatts_send_indicate(gatts_if, gl_profile_tab[IMU_PROFILE_APP_ID].conn_id, gl_profile_tab[IMU_PROFILE_APP_ID].char_handle, sizeof(notify_data), notify_data, false);
            if (ret) {
                ESP_LOGE(GATTS_TAG, "send notify failed, error code = %x", ret);
            }
        }
        break;
    default:
        break;
    }
}

static void motor_gatts_profile_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
{
    switch (event) {
    case ESP_GATTS_REG_EVT:
        ESP_LOGI(GATTS_TAG, "GATT server register, status %d, app_id %d", param->reg.status, param->reg.app_id);
        gl_profile_tab[MOTOR_PROFILE_APP_ID].service_id.is_primary = true;
        gl_profile_tab[MOTOR_PROFILE_APP_ID].service_id.id.inst_id = 0x00;
        gl_profile_tab[MOTOR_PROFILE_APP_ID].service_id.id.uuid.len = ESP_UUID_LEN_16;
        gl_profile_tab[MOTOR_PROFILE_APP_ID].service_id.id.uuid.uuid.uuid16 = MOTOR_SVC_UUID;
        esp_ble_gatts_create_service(gatts_if, &gl_profile_tab[MOTOR_PROFILE_APP_ID].service_id, MOTOR_NUM_HANDLE);
        break;
    case ESP_GATTS_CREATE_EVT:
        //service has been created, now add characteristic declaration
        ESP_LOGI(GATTS_TAG, "Service create, status %d, service_handle %d", param->create.status, param->create.service_handle);
        gl_profile_tab[MOTOR_PROFILE_APP_ID].service_handle = param->create.service_handle;
        gl_profile_tab[MOTOR_PROFILE_APP_ID].char_uuid.len = ESP_UUID_LEN_16;
        gl_profile_tab[MOTOR_PROFILE_APP_ID].char_uuid.uuid.uuid16 = MOTOR_CHAR_UUID;

        esp_ble_gatts_start_service(gl_profile_tab[MOTOR_PROFILE_APP_ID].service_handle);
        // Motor characteristic now write-only: commands are sent to motor task
        motor_property = ESP_GATT_CHAR_PROP_BIT_WRITE;
        esp_err_t ret = esp_ble_gatts_add_char(gl_profile_tab[MOTOR_PROFILE_APP_ID].service_handle, &gl_profile_tab[MOTOR_PROFILE_APP_ID].char_uuid,
                            ESP_GATT_PERM_WRITE ,
                            motor_property,
                            NULL, NULL);
        if (ret) {
            ESP_LOGE(GATTS_TAG, "add char failed, error code = %x", ret);
        }
        break;
    case ESP_GATTS_ADD_CHAR_EVT:
        ESP_LOGI(GATTS_TAG, "Characteristic add, status %d, attr_handle %d, char_uuid %x",
                 param->add_char.status, param->add_char.attr_handle, param->add_char.char_uuid.uuid.uuid16);
        gl_profile_tab[MOTOR_PROFILE_APP_ID].char_handle = param->add_char.attr_handle;
        break;
    case ESP_GATTS_ADD_CHAR_DESCR_EVT:
        ESP_LOGI(GATTS_TAG, "Descriptor add, status %d", param->add_char_descr.status);
        gl_profile_tab[MOTOR_PROFILE_APP_ID].descr_handle = param->add_char_descr.attr_handle;
        motor_create_cmpl = true;
        break;
    case ESP_GATTS_READ_EVT:
        // Read is no longer supported for Motor characteristic
        ESP_LOGI(GATTS_TAG, "Motor characteristic read not supported");
        break;
    case ESP_GATTS_WRITE_EVT:
        ESP_LOGI(GATTS_TAG, "Motor write, len %u", param->write.len);
        ESP_LOG_BUFFER_HEX(GATTS_TAG, param->write.value, param->write.len);
        if (param->write.len >= 1) {
            uint8_t cmd = param->write.value[0];
            switch (cmd) {
            case 0x01: // 左移：MOTOR_ACTON_POS
                xTaskNotify(motor_control_task_handle, MOTOR_ACTON_POS, eSetValueWithOverwrite);
                ESP_LOGI(GATTS_TAG, "Motor action POS notified");
                break;
            case 0x02: // 右移：MOTOR_ACTON_NEG
                xTaskNotify(motor_control_task_handle, MOTOR_ACTON_NEG, eSetValueWithOverwrite);
                ESP_LOGI(GATTS_TAG, "Motor action NEG notified");
                break;
            case 0x03: // 翻转：MOTOR_ACTON_BOTH
                xTaskNotify(motor_control_task_handle, MOTOR_ACTON_BOTH, eSetValueWithOverwrite);
                ESP_LOGI(GATTS_TAG, "Motor action BOTH notified");
                break;
            default:
                ESP_LOGW(GATTS_TAG, "Unknown motor command: 0x%02X", cmd);
                break;
            }
        }
        example_write_event_env(gatts_if, param);
        break;
    case ESP_GATTS_DELETE_EVT:
        break;
    case ESP_GATTS_START_EVT:
        ESP_LOGI(GATTS_TAG, "Service start, status %d, service_handle %d", param->start.status, param->start.service_handle);
        break;
    case ESP_GATTS_STOP_EVT:
        break;
    case ESP_GATTS_CONNECT_EVT:
        esp_ble_conn_update_params_t conn_params = {0};
        memcpy(conn_params.bda, param->connect.remote_bda, sizeof(esp_bd_addr_t));
        conn_params.latency = 0;
        conn_params.max_int = 0x20;
        conn_params.min_int = 0x10;
        conn_params.timeout = 400;
        ESP_LOGI(GATTS_TAG, "Connected, conn_id %u, remote "ESP_BD_ADDR_STR"",
                param->connect.conn_id, ESP_BD_ADDR_HEX(param->connect.remote_bda));
        gl_profile_tab[MOTOR_PROFILE_APP_ID].conn_id = param->connect.conn_id;
        esp_ble_gap_update_conn_params(&conn_params);
        break;
    case ESP_GATTS_DISCONNECT_EVT:
        ESP_LOGI(GATTS_TAG, "Disconnected, remote "ESP_BD_ADDR_STR", reason 0x%02x",
                 ESP_BD_ADDR_HEX(param->disconnect.remote_bda), param->disconnect.reason);
        break;
    case ESP_GATTS_CONF_EVT:
        ESP_LOGI(GATTS_TAG, "Confirm receive, status %d, attr_handle %d", param->conf.status, param->conf.handle);
        if (param->conf.status != ESP_GATT_OK) {
            ESP_LOG_BUFFER_HEX(GATTS_TAG, param->conf.value, param->conf.len);
        }
        break;
    default:
        break;
    }
}

static void atomizer_gatts_profile_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
{
    switch (event) {
    case ESP_GATTS_REG_EVT:
        ESP_LOGI(GATTS_TAG, "GATT server register, status %d, app_id %d", param->reg.status, param->reg.app_id);
        gl_profile_tab[ATOMIZER_PROFILE_APP_ID].service_id.is_primary = true;
        gl_profile_tab[ATOMIZER_PROFILE_APP_ID].service_id.id.inst_id = 0x00;
        gl_profile_tab[ATOMIZER_PROFILE_APP_ID].service_id.id.uuid.len = ESP_UUID_LEN_16;
        gl_profile_tab[ATOMIZER_PROFILE_APP_ID].service_id.id.uuid.uuid.uuid16 = ATOMIZER_SVC_UUID;
        esp_ble_gatts_create_service(gatts_if, &gl_profile_tab[ATOMIZER_PROFILE_APP_ID].service_id, ATOMIZER_NUM_HANDLE);
        break;
    case ESP_GATTS_CREATE_EVT:
        //service has been created, now add characteristic declaration
        ESP_LOGI(GATTS_TAG, "Service create, status %d, service_handle %d", param->create.status, param->create.service_handle);
        gl_profile_tab[ATOMIZER_PROFILE_APP_ID].service_handle = param->create.service_handle;
        // 使用LED UUID让nRF Connect显示ON/OFF开关
        gl_profile_tab[ATOMIZER_PROFILE_APP_ID].char_uuid.len = ESP_UUID_LEN_128;
        memcpy(gl_profile_tab[ATOMIZER_PROFILE_APP_ID].char_uuid.uuid.uuid128, led_chr_uuid, ESP_UUID_LEN_128);

        esp_ble_gatts_start_service(gl_profile_tab[ATOMIZER_PROFILE_APP_ID].service_handle);
        atomizer_property = ESP_GATT_CHAR_PROP_BIT_WRITE | ESP_GATT_CHAR_PROP_BIT_READ;
        esp_err_t ret = esp_ble_gatts_add_char(gl_profile_tab[ATOMIZER_PROFILE_APP_ID].service_handle, &gl_profile_tab[ATOMIZER_PROFILE_APP_ID].char_uuid,
                            ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE ,
                            atomizer_property,
                            &atomizer_status_attr, NULL);
        if (ret) {
            ESP_LOGE(GATTS_TAG, "add char failed, error code = %x", ret);
        }
        break;
    case ESP_GATTS_ADD_CHAR_EVT:
        ESP_LOGI(GATTS_TAG, "Characteristic add, status %d, attr_handle %d, char_uuid %x",
                 param->add_char.status, param->add_char.attr_handle, param->add_char.char_uuid.uuid.uuid16);
        gl_profile_tab[ATOMIZER_PROFILE_APP_ID].char_handle = param->add_char.attr_handle;
        break;
    case ESP_GATTS_ADD_CHAR_DESCR_EVT:
        ESP_LOGI(GATTS_TAG, "Descriptor add, status %d", param->add_char_descr.status);
        gl_profile_tab[ATOMIZER_PROFILE_APP_ID].descr_handle = param->add_char_descr.attr_handle;
        atomizer_create_cmpl = true;
        break;
    case ESP_GATTS_READ_EVT:
        ESP_LOGI(GATTS_TAG, "Atomizer characteristic read");
        esp_gatt_rsp_t rsp;
        memset(&rsp, 0, sizeof(esp_gatt_rsp_t));

        rsp.attr_value.handle = param->read.handle;
        rsp.attr_value.len = 1;
        // 返回雾化器状态：0x00=OFF, 0x01=ON
        rsp.attr_value.value[0] = atomizer1.enable_flag ? 0x01 : 0x00;
        ESP_LOGI(GATTS_TAG, "Atomizer status: %s", atomizer1.enable_flag ? "ON" : "OFF");
        esp_ble_gatts_send_response(gatts_if, param->read.conn_id, param->read.trans_id, ESP_GATT_OK, &rsp);
        break;
    case ESP_GATTS_WRITE_EVT:
        ESP_LOGI(GATTS_TAG, "Atomizer characteristic write, value len %u", param->write.len);
        ESP_LOG_BUFFER_HEX(GATTS_TAG, param->write.value, param->write.len);
        if (param->write.value[0]) {
            ESP_LOGI(GATTS_TAG, "ATOMIZER ON!");
            atomizer_on(&atomizer1);
        } else {
            ESP_LOGI(GATTS_TAG, "ATOMIZER OFF!");
            atomizer_off(&atomizer1);
        }
        example_write_event_env(gatts_if, param);
        break;
    case ESP_GATTS_DELETE_EVT:
        break;
    case ESP_GATTS_START_EVT:
        ESP_LOGI(GATTS_TAG, "Service start, status %d, service_handle %d", param->start.status, param->start.service_handle);
        break;
    case ESP_GATTS_STOP_EVT:
        break;
    case ESP_GATTS_CONNECT_EVT:
        esp_ble_conn_update_params_t conn_params = {0};
        memcpy(conn_params.bda, param->connect.remote_bda, sizeof(esp_bd_addr_t));
        conn_params.latency = 0;
        conn_params.max_int = 0x20;
        conn_params.min_int = 0x10;
        conn_params.timeout = 400;
        ESP_LOGI(GATTS_TAG, "Connected, conn_id %u, remote "ESP_BD_ADDR_STR"",
                param->connect.conn_id, ESP_BD_ADDR_HEX(param->connect.remote_bda));
        gl_profile_tab[ATOMIZER_PROFILE_APP_ID].conn_id = param->connect.conn_id;
        esp_ble_gap_update_conn_params(&conn_params);
        break;
    case ESP_GATTS_DISCONNECT_EVT:
        ESP_LOGI(GATTS_TAG, "Disconnected, remote "ESP_BD_ADDR_STR", reason 0x%02x",
                 ESP_BD_ADDR_HEX(param->disconnect.remote_bda), param->disconnect.reason);
        break;
    case ESP_GATTS_CONF_EVT:
        ESP_LOGI(GATTS_TAG, "Confirm receive, status %d, attr_handle %d", param->conf.status, param->conf.handle);
        if (param->conf.status != ESP_GATT_OK) {
            ESP_LOG_BUFFER_HEX(GATTS_TAG, param->conf.value, param->conf.len);
        }
        break;
    default:
        break;
    }
}

void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
{
    if (event == ESP_GATTS_REG_EVT) {
        if (param->reg.status == ESP_GATT_OK) {
            gl_profile_tab[param->reg.app_id].gatts_if = gatts_if;

        } else {
            ESP_LOGI(GATTS_TAG, "Reg app failed, app_id %04x, status %d",
                    param->reg.app_id,
                    param->reg.status);
            return;
        }
    }

    //gatts_if registered complete, call cb handlers
    do {
        int idx;
        for (idx = 0; idx < PROFILE_NUM; idx++) {
            if (gatts_if == ESP_GATT_IF_NONE || /* ESP_GATT_IF_NONE, not specify a certain gatt_if, need to call every profile cb function */
                    gatts_if == gl_profile_tab[idx].gatts_if) {
                if (gl_profile_tab[idx].gatts_cb) {
                    gl_profile_tab[idx].gatts_cb(event, gatts_if, param);
                }
            }
        }
    } while(0);
}

esp_err_t ble_init(void)
{
    esp_err_t ret;

    ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT));

    esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
    ret                               = esp_bt_controller_init(&bt_cfg);
    if (ret) {
        ESP_LOGE(GATTS_TAG, "%s initialize controller failed: %s", __func__, esp_err_to_name(ret));
        return ret;
    }

    ret = esp_bt_controller_enable(ESP_BT_MODE_BLE);
    if (ret) {
        ESP_LOGE(GATTS_TAG, "%s enable controller failed: %s", __func__, esp_err_to_name(ret));
        return ret;
    }

    ret = esp_bluedroid_init();
    if (ret) {
        ESP_LOGE(GATTS_TAG, "%s init bluetooth failed: %s", __func__, esp_err_to_name(ret));
        return ret;
    }

    ret = esp_bluedroid_enable();
    if (ret) {
        ESP_LOGE(GATTS_TAG, "%s enable bluetooth failed: %s", __func__, esp_err_to_name(ret));
        return ret;
    }

    ret = esp_ble_gap_register_callback(gap_event_handler);
    if (ret) {
        ESP_LOGE(GATTS_TAG, "gap register error, error code = %x", ret);
        return ret;
    }

    // 配置BLE安全参数（启用bonding）
    // esp_ble_auth_req_t auth_req = ESP_LE_AUTH_REQ_SC_MITM_BOND;  // 安全连接 + MITM保护 + Bonding
    // esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE;                    // 无IO能力（无需PIN码输入）
    // uint8_t key_size = 16;                                        // 加密密钥大小
    // uint8_t init_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK;
    // uint8_t rsp_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK;
    // uint8_t auth_option = ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE;
    // uint8_t oob_support = ESP_BLE_OOB_DISABLE;
    
    // esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &auth_req, sizeof(uint8_t));
    // esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t));
    // esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &key_size, sizeof(uint8_t));
    // esp_ble_gap_set_security_param(ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH, &auth_option, sizeof(uint8_t));
    // esp_ble_gap_set_security_param(ESP_BLE_SM_OOB_SUPPORT, &oob_support, sizeof(uint8_t));
    // esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &init_key, sizeof(uint8_t));
    // esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &rsp_key, sizeof(uint8_t));
    // ESP_LOGI(GATTS_TAG, "BLE security configured with bonding enabled");

    ret = esp_ble_gatts_register_callback(gatts_event_handler);
    if (ret) {
        ESP_LOGE(GATTS_TAG, "gatts register error, error code = %x", ret);
        return ret;
    }

    ret = esp_ble_gatts_app_register(IMU_PROFILE_APP_ID);
    if (ret) {
        ESP_LOGE(GATTS_TAG, "app register failed, error code = %x", ret);
        return ret;
    }
    ret = esp_ble_gatts_app_register(MOTOR_PROFILE_APP_ID);
    if (ret) {
        ESP_LOGE(GATTS_TAG, "app register failed, error code = %x", ret);
        return ret;
    }
    ret = esp_ble_gatts_app_register(ATOMIZER_PROFILE_APP_ID);
    if (ret) {
        ESP_LOGE(GATTS_TAG, "app register failed, error code = %x", ret);
        return ret;
    }
    ESP_LOGI(GATTS_TAG, "app register success");

    ret = esp_ble_gatt_set_local_mtu(500);
    if (ret) {
        ESP_LOGE(GATTS_TAG, "set local  MTU failed, error code = %x", ret);
    }
    
    return ESP_OK;
}
